﻿using Application.Interfaces.Mapping;
using AutoMapper;
using Omu.ValueInjecter;
using System.Collections.Generic;

namespace Infrastructure.Implementations.Mapping
{
    public class DefaultMapper : IMapper
    {
        public TDestination To<TSource, TDestination>(TSource source)
        {
            Mapper.CreateMap<TSource, TDestination>();
            return Mapper.Map<TSource, TDestination>(source);
        }

        public IEnumerable<T> To<S, T>(IEnumerable<S> source)
        {
            Mapper.CreateMap<S, T>();
            return Mapper.Map<IEnumerable<S>, IEnumerable<T>>(source);
        }

        public void From(object entity, params object[] source)
        {
            entity.InjectFrom(source);
        }

        public void FromSkipNull(object entity, params object[] source)
        {
            entity.InjectFrom<SkipNull>(source);
        }

        public class SkipNull : ConventionInjection
        {
            protected override bool Match(ConventionInfo c)
            {
                bool flag = c.SourceProp.Name == c.TargetProp.Name && c.SourceProp.Value != null;
                if (c.SourceProp.Type.IsEnum && c.TargetProp.Type.IsEnum)
                {
                    return flag;
                }
                else
                {
                    return flag && c.SourceProp.Type.FullName == c.TargetProp.Type.FullName;
                }
            }
        }
    }
}